<template>
  <el-card class="box-card" header="专科对应本科专业">
    <DataManageTable
      ref="tableRef"
      :tableConfig="tableConfig"
      @getTableData="getTableData"
      @saveRowEvent="saveRowEvent"
    >
      <template #customToolbarBtns>
        <vxe-button status="danger" @click="clearData">清空数据</vxe-button>
      </template>
    </DataManageTable>
  </el-card>
</template>

<script setup>
import { VXETable } from 'vxe-table'
import {
  getTableDataAsync,
  saveOrUpdateAsync,
  deleteAllAsync
} from '@/api/dataManage/juniorCollegeToUndergraduate'
import { useDataManage } from '@/hooks'
import tableConfig from './config/table.config'

const tableRef = ref()
const { getTableData, saveRowEvent } = useDataManage({
  getTableDataAsync,
  saveOrUpdateAsync,
  saveParamsCallBack,
  tableRef
})

function saveParamsCallBack(updateRow, row) {
  let params = null
  const {
    id,
    juniorCollegeCode,
    juniorCollegeName,
    undergraduateCode,
    undergraduateName,
    subjectDescription
  } = updateRow.length ? updateRow[0] : row
  params = {
    juniorCollegeCode,
    juniorCollegeName,
    undergraduateCode,
    undergraduateName,
    subjectDescription
  }
  // 有id表示是老数据，否则是新数据
  if (Object.hasOwn(row, 'id')) params.id = id
  return params
}

/** 清空数据 */
const clearData = async () => {
  const type = await VXETable.modal.confirm('您确定要删除所有数据吗？数据清空后无法恢复！')
  if (type === 'confirm') {
    try {
      const res = await deleteAllAsync()
      if (res.code === 200) {
        tableRef.value.getTableData()
        ElMessage.success('删除成功')
      }
    } catch (error) {
      console.error(error)
    }
  }
}
</script>

<style scoped lang="scss">
.box-card {
  height: 100%;

  :deep(.el-card__body) {
    height: calc(100% - 58px);
  }
}
</style>
